package org.gongliang.controller.sys;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.gongliang.common.annotation.KLog;
import org.gongliang.common.base.BaseController;
import org.gongliang.common.base.Result;
import org.gongliang.common.exception.ExceptionEnum;
import org.gongliang.common.web.csrf.CsrfToken;
import org.gongliang.kit.str.StrKit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;

import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping(value = "/sys")
@ApiIgnore
public class LoginController extends BaseController {

	@GetMapping("/updatePwdPage")
	public String updatePwdPage() {
		return "password";
	}
	/**
	 * 登录页面
	 */
	@GetMapping("/login")
	@CsrfToken(create = true)
	public String login() {
		if (SecurityUtils.getSubject().isAuthenticated()) {
			return "index";
		}
		return "login";
	}

	/**
	 * 未授权
	 * 
	 * @return {String}
	 */
	@GetMapping("/unauth")
	public String unauth() {
		if (SecurityUtils.getSubject().isAuthenticated() == false) {
			return "redirect:/login";
		}
		return "unauth";
	}

	/**
	 * 用户登陆
	 */
	@PostMapping("/login")
	@CsrfToken(remove = true)
	@ResponseBody
	@KLog("用户登录")
	public Result login(HttpServletRequest request, String username, String password, String captcha,
			@RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
		Result result = Result.success();
		// 改为全部抛出异常，避免ajax csrf token被刷新
		if (StringUtils.isBlank(username)) {
			return Result.error(ExceptionEnum.USERNAME_NOT_NULL);
		}
		if (StringUtils.isBlank(password)) {
			return Result.error(ExceptionEnum.PARAM_NOT_NULL);
		}
		if (StrKit.isBlank(captcha)) {
			return Result.error(ExceptionEnum.KAPTCHA_NOT_NULL);
		}
		if (!validate(request, captcha)) {
			return Result.error(ExceptionEnum.KAPTCHA_ERROR);
		}
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		// 设置记住密码
		token.setRememberMe(1 == rememberMe);
		try {
			user.login(token);
			return Result.success("登录成功!");
		} catch (UnknownAccountException e) {
			result = Result.error(ExceptionEnum.NO_THIS_USER);
		} catch (DisabledAccountException e) {
			result = Result.error(ExceptionEnum.ACCOUNT_FREEZED);
		} catch (IncorrectCredentialsException e) {
			result = Result.error(ExceptionEnum.USER_PWD_ERROR);
		} catch (Throwable e) {
			result = Result.error("其它异常:" + e.getMessage());
		}
		return result;
	}


	private boolean validate(HttpServletRequest request, String captcha) {
		String sessionCaptcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		return captcha.equals(sessionCaptcha);
	}
}
